//
//  AnnotationViewController.m
//  BaiduMapDemo
//
//  Created by iOS on 2017/8/22.
//  Copyright © 2017年 MS. All rights reserved.
//

#import "AnnotationViewController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>
#import "BMKClusterManager.h"

/*
 *点聚合Annotation
 */
@interface ClusterAnnotation : BMKPointAnnotation

///所包含annotation个数
@property (nonatomic, assign) NSInteger size;

/**
 存储云检索结果信息类
 */
@property (strong, nonatomic) BMKCloudPOIInfo *info;

@end

@implementation ClusterAnnotation


@end


/*
 *点聚合AnnotationView
 */
@interface ClusterAnnotationView : BMKPinAnnotationView

@property (nonatomic, assign) NSInteger size;
@property (nonatomic, strong) UILabel *label;

@end

@implementation ClusterAnnotationView


- (id)initWithAnnotation:(id<BMKAnnotation>)annotation
         reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    if (self)
    {
        [self setBounds:CGRectMake(0.f, 0.f, 22.f, 22.f)];
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, 22.f, 22.f)];
        _label.textColor = [UIColor whiteColor];
        _label.font = [UIFont systemFontOfSize:11];
        _label.textAlignment = NSTextAlignmentCenter;
        
        [self addSubview:_label];
        self.alpha = 0.85;
    }
    
    return self;
}

- (void)setSize:(NSInteger)size
{
    _size = size;
    if (_size == 1)
    {
        self.label.hidden = YES;
        self.pinColor = BMKPinAnnotationColorRed;
        return;
    }
    
    self.label.hidden = NO;
    
    if (size > 20)
    {
        self.label.backgroundColor = [UIColor redColor];
    }
    else if (size > 10)
    {
        self.label.backgroundColor = [UIColor purpleColor];
    }
    else if (size > 5)
    {
        self.label.backgroundColor = [UIColor blueColor];
    }
    else
    {
        self.label.backgroundColor = [UIColor greenColor];
    }
    
    _label.text = [NSString stringWithFormat:@"%ld", size];
}

@end

@interface AnnotationViewController () <BMKMapViewDelegate,BMKLocationServiceDelegate,BMKCloudSearchDelegate>
{
    BMKClusterManager *_clusterManager;///<点聚合管理类
    NSInteger _clusterZoom;///<聚合级别
    NSMutableArray *_clusterCaches;///< 点聚合缓存标注
    NSMutableArray *_allDataCaches;
}

@property (strong, nonatomic) BMKMapView *mapView;
@property (strong, nonatomic) BMKLocationService *locationService;
@property (strong, nonatomic) BMKCloudSearch *search;

@end

static NSString *const annotationViewReuseIdentifier = @"annotataionView";

@implementation AnnotationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"地图标注";
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 初始化点聚合管理类
    _clusterManager = [[BMKClusterManager alloc] init];
    _clusterCaches = [[NSMutableArray alloc] init];
    for (NSInteger i = 3; i < 22; i++) {
        [_clusterCaches addObject:[NSMutableArray array]];
    }
    
    _allDataCaches = [[NSMutableArray alloc] init];
    [self.locationService startUserLocationService];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
}

- (BMKMapView *)mapView
{
    if (!_mapView)
    {
        _mapView = [[BMKMapView alloc] init];
        _mapView.delegate = self;
        _mapView.mapType = BMKMapTypeStandard;
        _mapView.zoomLevel = 19;
        _mapView.showsUserLocation = YES;//显示定位图层
        
        [self.view addSubview:_mapView];
        
        [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(64, 0, 0, 0));
        }];
    }
    
    return _mapView;
}

- (BMKLocationService *)locationService
{
    if (!_locationService)
    {
        _locationService = [[BMKLocationService alloc]init];
        _locationService.delegate = self;
        _locationService.desiredAccuracy = kCLLocationAccuracyBest;
    }
    
    return _locationService;
}

- (BMKCloudSearch *)search
{
    if (!_search)
    {
        //初始化云检索服务
        _search = [[BMKCloudSearch alloc] init];
        _search.delegate = self;
    }
    
    return _search;
}


#pragma mark - BMKMapViewDelegate

- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(41.661549, 123.468634) animated:YES];
    
    // 关闭精度圈
//    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc] init];
//    displayParam.isAccuracyCircleShow = NO;//精度圈是否显示
//    [_mapView updateLocationViewWithParam:displayParam];
    
//    [self updateClusters];
}

/**
 *地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）都会调用此接口
 *@param mapView 地图View
 *@param status 此时地图的状态
 */
- (void)mapView:(BMKMapView *)mapView
 onDrawMapFrame:(BMKMapStatus *)status
{
    if (_clusterZoom != 0 && _clusterZoom != (NSInteger)mapView.zoomLevel)
    {
//        [self updateClusters];
    }
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView
             viewForAnnotation:(id <BMKAnnotation>)annotation
{
    /*
    // 检查是否有重用的缓存
    BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (!annotationView)
    {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = NO;
        UIImage *img = [UIImage imageNamed:@"AnnotationImg"];
        annotationView.image = img;
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
    */
    
    ClusterAnnotation *clusterAnnotation = (ClusterAnnotation *)annotation;
    ClusterAnnotationView *clusterAnnotationView = [[ClusterAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier];
    clusterAnnotationView.size = clusterAnnotation.size;
    clusterAnnotationView.draggable = YES;
    clusterAnnotationView.annotation = clusterAnnotation;
    
    if (clusterAnnotation.size == 1)
    {
        BMKCloudPOIInfo *info = clusterAnnotation.info;
        
        UIView *paopaoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 80)];
        paopaoView.backgroundColor = [UIColor whiteColor];
        [paopaoView.layer setMasksToBounds:YES];
        [paopaoView.layer setCornerRadius:3.0];
        paopaoView.alpha = 0.9;
        
        // logo
        UIImageView *logo = [[UIImageView alloc] init];
        logo.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img0.imgtn.bdimg.com/it/u=1870203556,2400775406&fm=200&gp=0.jpg"]]];
        
        [paopaoView addSubview:logo];
        
        [logo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.left.mas_equalTo(10);
            make.size.mas_equalTo(CGSizeMake(35, 35));
        }];
        
        // name
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.font = [UIFont systemFontOfSize:9];
        nameLabel.textColor = [UIColor lightGrayColor];
        nameLabel.text = info.title;
        
        [paopaoView addSubview:nameLabel];
        
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(logo);
            make.left.equalTo(logo.mas_right).offset(10);
            make.right.mas_equalTo(-10);
        }];
        
        // address
        UILabel *addressLabel = [[UILabel alloc] init];
        addressLabel.font = [UIFont systemFontOfSize:9];
        addressLabel.textColor = [UIColor lightGrayColor];
        addressLabel.text = info.address;
        
        [paopaoView addSubview:addressLabel];
        
        [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(logo);
            make.leading.equalTo(nameLabel);
            make.right.mas_equalTo(-10);
        }];
        
        // button
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"路线规划" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:9];
        btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        btn.layer.borderWidth = 0.5f;
        btn.layer.cornerRadius = 3.0f;
        btn.layer.masksToBounds = YES;
        
        [paopaoView addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(logo.mas_bottom).offset(8);
            make.leading.equalTo(logo);
            make.size.mas_equalTo(CGSizeMake(45, 18));
        }];
        
        BMKActionPaopaoView *actionPaopaoView = [[BMKActionPaopaoView alloc] initWithCustomView:paopaoView];
        actionPaopaoView.frame = CGRectMake(0, 0, 200, 80);
        
        clusterAnnotationView.paopaoView = actionPaopaoView;
    }
    
    return clusterAnnotationView;
}

- (void)mapView:(BMKMapView *)mapView
annotationViewForBubble:(BMKAnnotationView *)view
{
    if ([view isKindOfClass:[ClusterAnnotationView class]]) {
        ClusterAnnotation *clusterAnnotation = (ClusterAnnotation*)view.annotation;
        if (clusterAnnotation.size > 1) {
            [mapView setCenterCoordinate:view.annotation.coordinate];
            [mapView zoomIn];
        }
    }
}

//标注 单击事件
-(void)mapView:(BMKMapView *)mapView
didSelectAnnotationView:(BMKAnnotationView *)view
{
    if ([view isKindOfClass:[ClusterAnnotationView class]])
    {
        ClusterAnnotation *clusterAnnotation = (ClusterAnnotation*)view.annotation;
        if (clusterAnnotation.size > 1)
        {
            [mapView setCenterCoordinate:view.annotation.coordinate];
            [mapView zoomIn];
        }
        else
        {
            
        }
    }
    
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    CLLocationCoordinate2D centerCoordinate = [mapView convertPoint:mapView.center toCoordinateFromView:mapView];
    CLLocationCoordinate2D leftTopCoordinate = [mapView convertPoint:CGPointZero toCoordinateFromView:mapView];
    
    BMKMapPoint pointA = BMKMapPointForCoordinate(centerCoordinate);
    BMKMapPoint pointB = BMKMapPointForCoordinate(leftTopCoordinate);
    
    BMKCloudNearbySearchInfo *cloudLocalSearch = [[BMKCloudNearbySearchInfo alloc]init];
    cloudLocalSearch.ak = @"kw6s29DYyW2csS1HzO7yTN62hA7pouzG";
    cloudLocalSearch.geoTableId = 159605;
    cloudLocalSearch.radius = BMKMetersBetweenMapPoints(pointA, pointB);
    cloudLocalSearch.pageIndex = 0;
    cloudLocalSearch.pageSize = 50;
    cloudLocalSearch.location = [NSString stringWithFormat:@"%f,%f",centerCoordinate.longitude, centerCoordinate.latitude];
    BOOL flag = [self.search nearbySearchWithSearchInfo:cloudLocalSearch];
    if(flag)
    {
        NSLog(@"周边云检索发送成功");
        [_locationService stopUserLocationService];
    }
    else
    {
        NSLog(@"周边云检索发送失败");
    }
}


#pragma mark - BMKLocationServiceDelegate

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [self.mapView updateLocationData:userLocation];
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self.mapView updateLocationData:userLocation];
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    
}


#pragma mark - BMKCloudSearchDelegate

//返回云检索结果回调
- (void)onGetCloudPoiResult:(NSArray*)poiResultList
                 searchType:(int)type
                  errorCode:(int)error
{
    if (error == BMKErrorOk)
    {
        BMKCloudPOIList *result = [poiResultList objectAtIndex:0];
        for (int i = 0; i < result.POIs.count; i++)
        {
            /*
            BMKCloudPOIInfo* poi = [result.POIs objectAtIndex:i];
            
            BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
            CLLocationCoordinate2D pt = (CLLocationCoordinate2D){ poi.longitude,poi.latitude};
            annotation.coordinate = pt;
            annotation.title = poi.title;
            [_mapView addAnnotation:annotation];
            */
            
            BMKCloudPOIInfo *cloudPOIInfo = [result.POIs objectAtIndex:i];
            CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(cloudPOIInfo.longitude, cloudPOIInfo.latitude);
            
            BOOL flag = NO;
            for (BMKCloudPOIInfo *info in _allDataCaches)
            {
                if (info.uid == cloudPOIInfo.uid)
                {
                    flag = YES;
                    break;
                }
            }
            if (flag)
            {
                continue;
            }
            else
            {
                [_allDataCaches addObject:cloudPOIInfo];
            }
            // 点聚合
            // 向点聚合管理类中添加标注
            BMKClusterItem *clusterItem = [[BMKClusterItem alloc] init];
            clusterItem.coor = coordinate;
            clusterItem.info = cloudPOIInfo;
            [_clusterManager addClusterItem:clusterItem];
        }
        
        [self updateClusters];
    }
    else
    {
        NSLog(@"error ==%d",error);
    }
}


#pragma mark - 更新聚合状态

- (void)updateClusters
{
    _clusterZoom = (NSInteger)_mapView.zoomLevel;
    @synchronized(_clusterCaches)
    {
        __block NSMutableArray *clusters = [_clusterCaches objectAtIndex:(_clusterZoom - 3)];
        
        if (clusters.count > 0)
        {
            [_mapView removeAnnotations:_mapView.annotations];
            [_mapView addAnnotations:clusters];
        }
        else
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                ///获取聚合后的标注
                __block NSArray *array = [_clusterManager getClusters:_clusterZoom];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    for (BMKCluster *item in array)
                    {
                        ClusterAnnotation *annotation = [[ClusterAnnotation alloc] init];
                        annotation.coordinate = item.coordinate;
                        annotation.size = item.size;
                        if (item.size > 1)
                        {
                            annotation.title = [NSString stringWithFormat:@"%ld", item.size];
                        }
                        else
                        {
                            BMKClusterItem *clusterItem = [item.clusterItems firstObject];
                            annotation.title = clusterItem.info.title;
                            
                            annotation.info = clusterItem.info;
                        }
                        [clusters addObject:annotation];
                    }
                    [_mapView removeAnnotations:_mapView.annotations];
                    [_mapView addAnnotations:clusters];
                });
            });
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.mapView.delegate = nil;
    self.mapView = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

